package file;

import java.io.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA
 * Description：复制一个普通文件
 * User：chenshu
 * Date：2023-11-15
 * Time：23:33
 */
public class Demo8 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要复制的文件路径：");
        String srcPath = scanner.next();
        File srcFile = new File(srcPath);
        if(!srcFile.exists()) {
            System.out.println("文件不存在，无法复制");
            return;
        }
        if (!srcFile.isFile()) {
            System.out.println("不是普通文件，无法复制");
            return;
        }
        System.out.println("请输入要复制的目标路径：");
        String destPath = scanner.next();
        File destFile = new File(destPath);
        if (destFile.exists()) {
            System.out.println("复制的文件已存在");
            return;
        }
        try(InputStream inputStream = new FileInputStream(srcFile)) {
            try(OutputStream outputStream = new FileOutputStream(destFile)) {
                byte[] buf = new byte[1024];
                while (true) {
                    int len = inputStream.read(buf);
                    if (len == -1) {
                        break;
                    }
                    outputStream.write(buf, 0, len);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        System.out.println("复制完成！");
    }
}
